//
//  DHOfficialController.m
//  宏达APP
//
//  Created by DIANGHONG on 2018/4/27.
//  Copyright © 2018年 123. All rights reserved.
//

#import "DHOfficialController.h"
#import "DHSortView.h"
#import "DHNetworkManager+DHHodaNetworkManager.h"
#import "DHGoodListViewModel.h"
#import "DHGoodCell.h"
#import <MJRefresh/MJRefreshGifHeader.h>
#import <MJRefresh/MJRefreshFooter.h>
#import <MJRefreshAutoGifFooter.h>
#import <MJRefresh/MJRefreshAutoNormalFooter.h>
#import <SVProgressHUD.h>
#import "UIViewController+CWLateralSlide.h"


#define kScreenWidth UIScreen.mainScreen.bounds.size.width
#define kScreenHeight UIScreen.mainScreen.bounds.size.height
#define kFilterViewWidth kScreenWidth * 0.666
#define KIsiPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)


NSString *goodCellID = @"gridGoodCellID";
NSString *listGoodCellID = @"listGoodCellID";
@interface DHOfficialController ()<UICollectionViewDataSource ,UICollectionViewDelegate, DHGoodCellDelegate>

//@property(nonatomic ,strong)NSArray *listModel;

@property(nonatomic ,strong)DHSortView *sortView;

@property(nonatomic ,strong)DHGoodListViewModel *listViewModel; // 视图模型

@property(nonatomic ,strong)UICollectionView *goodListView; // 商品界面

@property(nonatomic ,assign,getter=isPullUP)BOOL pullUP; //是否上拉刷新

@property(nonatomic ,assign,getter=isGrid)BOOL grid; // 商品界面的布局模式

@property(nonatomic ,strong)UIView *filterView; // 筛选界面

@end

@implementation DHOfficialController

- (UIView *)filterView{
    if (!_filterView) {
        _filterView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.view.frame), 0, kFilterViewWidth, kScreenHeight)];
        _filterView.backgroundColor = UIColor.redColor;
    }
    return _filterView;
}

// 懒加载 listViewModel
- (DHGoodListViewModel *)listViewModel{
    if (!_listViewModel) {
        _listViewModel = [[DHGoodListViewModel alloc] init];
    }
    return _listViewModel;
}

// 懒加载goodListView
- (UICollectionView *)goodListView{
    if (!_goodListView) {
        
        self.sortView.frame = CGRectMake(0, CGRectGetMaxY(self.navigationController.navigationBar.frame), kScreenWidth, 34);

        //创建流水布局
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        NSLog(@"%f",CGRectGetMaxY(self.sortView.frame));
        _goodListView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,
                                                                           0,
                                                                           kScreenWidth,
                                                                          kScreenHeight - CGRectGetMaxY(self.sortView.frame))
                                                                collectionViewLayout:layout];
        
        //设置布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.itemSize = CGSizeMake(kScreenWidth / 2,_goodListView.bounds.size.height / 3);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        _goodListView.alwaysBounceVertical =true;
        
        self.grid = NO;
        
        //设置代理
        _goodListView.dataSource = self;
        _goodListView.delegate = self;
        _goodListView.backgroundColor = UIColor.whiteColor;
        _goodListView.showsHorizontalScrollIndicator = false;
        _goodListView.contentSize = CGSizeMake(kScreenWidth, _goodListView.bounds.size.height);
    }
    return _goodListView;
}
#pragma mark： - 懒加载排序界面
- (DHSortView *)sortView{
    if (!_sortView) {
        _sortView = [DHSortView sortView];
        
        __weak typeof(self) WeakSelf = self;
        _sortView.viewPresentMode = ^(BOOL isGrid) {
            
            WeakSelf.grid = isGrid;
            
            [WeakSelf.goodListView reloadData];
        };
        
        // 对视图数组排序
        self.sortView.sortoderListGoodBlock = ^(ListSortorder sortorder) {
            
            switch (sortorder) {
                case ListSortorderDefault:
                    WeakSelf.listViewModel = nil;
                    [WeakSelf loadDataWithPullup:NO key:@(sortorder) oder:@(WeakSelf.sortView.oder) plan_id:nil gc_id:nil];
                    //[self.goodListView.mj_header beginRefreshing];
                    //[WeakSelf.goodListView reloadData];
                    break;
                case ListSortorderNone:
                    break;
                case ListSortorderHightToLowPrice:
        
                    WeakSelf.listViewModel = nil;
                    NSLog(@"%d",sortorder);
                    [WeakSelf loadDataWithPullup:NO key:@(sortorder + 1) oder:@(WeakSelf.sortView.oder) plan_id:nil gc_id:nil];
                    WeakSelf.sortView.sortKey = ListSortorderLowToHightPrice;
                    break;
                case ListSortorderLowToHightPrice:
                    WeakSelf.listViewModel = nil;
                    [WeakSelf loadDataWithPullup:NO key:@(sortorder) oder:@(WeakSelf.sortView.oder) plan_id:nil gc_id:nil];
                        break;
                case ListSortorderPopWay:
                    //FIXME: - 按照人气排序
                    WeakSelf.listViewModel = nil;
                    [WeakSelf loadDataWithPullup:NO key:@(WeakSelf.sortView.sortKey) oder:@(WeakSelf.sortView.oder) plan_id:nil gc_id:nil];
                    break;
            }
        };
        
        self.sortView.showFilterView = ^{
            
            UIViewController *vc = [[UIViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];

            vc.view.backgroundColor = UIColor.redColor;
            CWLateralSlideConfiguration *cw = [CWLateralSlideConfiguration configurationWithDistance:0 maskAlpha:0.4 scaleY:0.8 direction:CWDrawerTransitionFromRight backImage:nil];
            [WeakSelf cw_showDrawerViewController:nav animationType:1 configuration:cw];
  
        };

    }
    return _sortView;
}



- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.view bringSubviewToFront:self.sortView];
}

#pragma mark: - 设置navbar
- (void)setupNavBar{
    
    UIButton *popButton = [[UIButton alloc] init];
    [popButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [popButton addTarget:self action:@selector(popVC) forControlEvents:UIControlEventTouchUpInside];
    [popButton.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [popButton setContentEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 0)];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:popButton];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"配置单" style:UIBarButtonItemStylePlain target:self action:@selector(configButtonClick)];
    
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} forState:UIControlStateNormal];
    self.navigationController.navigationBar.tintColor = UIColor.blackColor;
    [self.navigationController.navigationBar setTitleTextAttributes: @{NSFontAttributeName : [UIFont systemFontOfSize:16]}];
  
}

#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNavBar];
    
    // 排序界面
    [self.view addSubview:self.sortView];
    // 商品列表界面
    [self.view addSubview:self.goodListView];
    // 筛选界面
   // [self.view insertSubview:self.filterView aboveSubview:self.navigationController.view];
    
    self.sortView.sortKey = ListSortorderDefault;
    
    [self.view setBackgroundColor:[UIColor lightGrayColor]];
    
    //注册可重用cell
    [self.goodListView registerNib:[UINib nibWithNibName:@"DHGoodCell" bundle:nil] forCellWithReuseIdentifier:goodCellID];
    [self.goodListView registerNib:[UINib nibWithNibName:@"DHListGoodCell" bundle:nil] forCellWithReuseIdentifier:listGoodCellID];
    
    //设置刷新控件
    [self setupRefreshedControl];
}
// 设置刷新控件
- (void)setupRefreshedControl{
    
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        [self loadDataWithPullup:NO key:@(self.sortView.sortKey) oder:@(self.sortView.oder) plan_id:nil gc_id:nil];
    }];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadDataWithPullup:YES key:@(self.sortView.sortKey) oder:@(self.sortView.oder) plan_id:nil gc_id:nil];
    }];
    
    footer.refreshingTitleHidden = true;
    
    self.goodListView.mj_header = header;
    self.goodListView.mj_footer = footer;
    [header setTitle:@"使劲下拉..." forState:MJRefreshStateIdle];
    [header setTitle:@"松手开始刷新..." forState:MJRefreshStatePulling];
    [header setTitle:@"开始刷新..." forState:MJRefreshStateRefreshing];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.mj_size = CGSizeMake(kScreenWidth, 80);
    
    [header beginRefreshing];
    
    [footer setTitle:@"使劲下拉..." forState:MJRefreshStateIdle];
    [footer setTitle:@"松手开始刷新..." forState:MJRefreshStatePulling];
    [footer setTitle:@"开始刷新..." forState:MJRefreshStateRefreshing];
    [footer setTitle:@"没有更多..." forState:MJRefreshStateNoMoreData];
}
#pragma mark: - 加载数据
- (void)loadDataWithPullup:(BOOL)pullUP key:(NSNumber *)key oder:(NSNumber *)oder plan_id:(NSNumber *)plan_id gc_id:(NSNumber *)gc_id{
    
    [self.listViewModel loadGoodListIsPullUP:pullUP key:key oder:oder plan_id:plan_id gc_id:gc_id finishedBlock:^(BOOL Success, BOOL noMoreData) {
        if (!Success) {
            [self.goodListView.mj_header endRefreshing];
            return ;
        }
        if (noMoreData) {
            [self.goodListView.mj_footer endRefreshingWithNoMoreData];
            [self.goodListView.mj_header endRefreshing];
            return;
        }
        
        //刷新collectionView
        [self.goodListView reloadData];
        
        [self.goodListView.mj_header endRefreshing];
        [self.goodListView.mj_footer endRefreshing];
    }];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    [self setupLayout];
}

#pragma mark: - 布局子视图
- (void)setupLayout{
    
    self.sortView.frame = CGRectMake(0, CGRectGetMaxY(self.navigationController.navigationBar.frame), kScreenWidth, 34);
    
    self.goodListView.frame = CGRectMake(0,
                                          CGRectGetMaxY(self.sortView.frame),
                                         kScreenWidth,
                                        kScreenHeight-  CGRectGetMaxY(self.sortView.frame));

    
}





#pragma mark: - 返回按钮监听
- (void)popVC{
    [self dismissViewControllerAnimated:true completion:nil];
}

#pragma mark: - 配置清单按钮监听
- (void)configButtonClick{
    //FIXME: - 未实现
}

#pragma mark: - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.listViewModel.listModel.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    //选择展示产品界面模式
    NSString *cellid = self.isGrid ? goodCellID : listGoodCellID;
    
    DHGoodCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellid forIndexPath:indexPath];
    
    cell.model = self.listViewModel.listModel[indexPath.row];
    cell.delegate = self;
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGSize itemSize = self.isGrid ? CGSizeMake(kScreenWidth / 2, collectionView.bounds.size.height / 3) : CGSizeMake(kScreenWidth, collectionView.bounds.size.height / 6);
    
    return itemSize;
}
#pragma mark: - 选用按钮的代理监听
- (void)goodCellTapSelectedButton:(DHGoodCell *)cell good:(DHGoodListModel *)good{
    
    // 发送网络请求
    [DHNetworkManager.shareManager postGoodToServiceWithKey:[DHNetworkManager.shareManager.account key] goods_id:good.goods_id.intValue plan_id:self.listViewModel.planInfo.plan_id.intValue gc_id:self.listViewModel.planInfo.class_list.firstObject.gc_id finishedBlock:^(BOOL isSuccess,NSString *isSuccessTips) {
        //NSLog(@"%d",isSuccess);
        if (!isSuccess) {
            return ;
        }
        if ([isSuccessTips isEqualToString:@"操作成功"]) {
            [SVProgressHUD showSuccessWithStatus:isSuccessTips];
            return;
        }
        [SVProgressHUD showSuccessWithStatus:isSuccessTips];
    }];
}


@end
